package com.banciyuan.bcywebview.biz.start;

import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.banciyuan.bcywebview.R;
import com.banciyuan.bcywebview.base.activity.BaseActivity;
import com.banciyuan.bcywebview.base.helper.data.UserDataHelper;
import com.banciyuan.bcywebview.base.helper.push.PushDataHelper;
import com.banciyuan.bcywebview.base.service.CleanAliasService;
import com.banciyuan.bcywebview.base.service.CleanService;
import com.banciyuan.bcywebview.base.service.InitBackGroundService;
import com.banciyuan.bcywebview.biz.apprecommend.RecommendAcgActivity;
import com.banciyuan.bcywebview.utils.common.UIUtils;
import com.banciyuan.bcywebview.utils.intent.gotoUtil;
import com.banciyuan.bcywebview.utils.sp.SPConstant;
import com.banciyuan.bcywebview.utils.sp.SPHelper;
import com.banciyuan.bcywebview.utils.universalimageloader.core.ImageLoader;
import com.google.gson.Gson;

import java.io.File;

import de.greenrobot.daoexample.model.StartUpInfo;

/**
 * Created by hfxt2008 on 14-12-11.
 * <p>
 * 入口，第一个显示的activity，只有一个和visitor一样的背景画面，主要是为了实现和lofter一样的交互
 * 判断是否登陆，然后如果未登陆visitor就fade_in，如果登陆就跳mainactivity
 */
public class StartActivity extends BaseActivity {

    private ImageLoader imageLoader;
    private ImageView mImageView;
    private ImageView mChannelImage;
    private View viewSkip;
    private long DEFAULT_STAYTIME = 3000;
    private boolean is_click;

    private boolean isShowRecommend() {
        return SPHelper.getBoolean(this, SPConstant.BCY_SHOWRECOMMEND, false);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.start_layout);
        initArgs();
        initUi();
        initData();
    }

    @Override
    protected void initData() {
        loadImage();
        cleanCache();
        showChannelLogo();
    }

    private void showChannelLogo() {
        int showCount = SPHelper.getInt(this, SPConstant.SPNAME_INITBACKGROUND, SPConstant.SHOW_CHANNEL_COUNT + getVersion(), 0);
        if (showCount < 1) {
            setChannelLogoImage();
            showCount++;
            SPHelper.putInt(this, SPConstant.SPNAME_INITBACKGROUND, SPConstant.SHOW_CHANNEL_COUNT + getVersion(), showCount);
        }
    }

    private void setChannelLogoImage() {
        Bitmap channelBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.channel_logo);
        if (null != channelBitmap) {
            LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) mChannelImage.getLayoutParams();
            layoutParams.width = UIUtils.dip2px(144, this);
            layoutParams.height = UIUtils.dip2px(45, this);
            mChannelImage.setLayoutParams(layoutParams);
            mChannelImage.setImageBitmap(channelBitmap);
        }
    }

    private String getVersion() {
        try {
            return getPackageManager().getPackageInfo(getPackageName(), 0).versionName;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return "";
    }

    private void cleanCache() {
        if (!SPHelper.getBoolean(this, SPConstant.SPNAME_CLEANTASK, SPConstant.CLEAR, false)) {
            startClean();
        }
    }

    private void cleanAlias() {
        if (!SPHelper.getBoolean(this, SPConstant.SPNAME_CLEANTASK, SPConstant.Alias, false)) {
            startCleanAlias();
        }
    }

    @Override
    protected void initUi() {
        mImageView = (ImageView) findViewById(R.id.background);
        mChannelImage = (ImageView) findViewById(R.id.iv_channel_logo);
        viewSkip = findViewById(R.id.tv_skip);
    }

    @Override
    protected void initArgs() {
        imageLoader = ImageLoader.getInstance();
    }

    private void loadImage() {
        String url = SPHelper.getString(this, SPConstant.SPNAME_INITBACKURL, SPConstant.URL, "");
        String startUpInfoStr = SPHelper.getString(this, SPConstant.SPNAME_INITBACKURL, SPConstant.STARTUP_PAGE_INFOR, "{}");
        final StartUpInfo startUpInfo = new Gson().fromJson(startUpInfoStr, StartUpInfo.class);
        if (!TextUtils.isEmpty(url)) {
            File file = new File(url);
            if (file.exists()) {
                mImageView.setImageBitmap(BitmapFactory.decodeFile(file.getAbsolutePath()));
            } else {
                mImageView.setImageResource(R.drawable.loading_default);
            }
            if (null != startUpInfo) {
                dealImageClickListener(startUpInfo);
                dealSkipClickListener(startUpInfo);
                dealSkipTime(startUpInfo);
            } else {
                enterNextActivity(DEFAULT_STAYTIME);
            }
        } else {
            mImageView.setImageResource(R.drawable.loading_default);
            enterNextActivity(DEFAULT_STAYTIME);
        }
        Intent intent = new Intent(StartActivity.this, InitBackGroundService.class);
        startService(intent);
    }

    private void dealSkipClickListener(StartUpInfo startUpInfo) {
        if (startUpInfo.isCan_skip()) {
            viewSkip.setVisibility(View.VISIBLE);
            viewSkip.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    is_click = true;
                    enterNextActivity();
                }
            });
        }
    }

    private void dealSkipTime(StartUpInfo startUpInfo) {
        if (startUpInfo.isCan_skip()) {
            mImageView.postDelayed(new Runnable() {
                @Override
                public void run() {
                    if (!is_click) {
                        enterNextActivity();
                    }
                }
            }, startUpInfo.getWait_sec() * 1000);
        } else {
            mImageView.postDelayed(new Runnable() {
                @Override
                public void run() {
                    if (!is_click) {
                        enterNextActivity();
                    }
                }
            }, 2000);
        }
    }

    private void dealImageClickListener(final StartUpInfo startUpInfo) {
        mImageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                is_click = true;
                if (!TextUtils.isEmpty(startUpInfo.getCode())) {
                    enterNextActivity();
                    PushDataHelper.processInnerPushData(StartActivity.this, startUpInfo.getCode());
                }
            }
        });
    }

    private void enterNextActivity() {
        if (UserDataHelper.ifLogin(StartActivity.this)) {
            if (isShowRecommend()) {
                gotoUtil.replaceMainClearTop(StartActivity.this);
                overridePendingTransition(R.anim.base_fade_in, R.anim.base_fade_out);
            } else {
                gotoUtil.replaceActAmin(StartActivity.this, RecommendAcgActivity.class, R.anim.base_fade_in, R.anim.base_fade_out);
            }
        } else {
            if (!isFinishing()) {
                gotoUtil.replaceLogin(StartActivity.this);
            }
            overridePendingTransition(R.anim.base_fade_in, R.anim.base_fade_out);
        }
    }

    private void enterNextActivity(long time) {
        if (UserDataHelper.ifLogin(this)) {
            if (isShowRecommend()) {
                mImageView.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        gotoUtil.replaceMainClearTop(StartActivity.this);
                        overridePendingTransition(R.anim.base_fade_in, R.anim.base_fade_out);
                    }
                }, time);
            } else {
                mImageView.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        gotoUtil.replaceActAmin(StartActivity.this, RecommendAcgActivity.class, R.anim.base_fade_in, R.anim.base_fade_out);
                    }
                }, time);
            }
        } else {
            mImageView.postDelayed(new Runnable() {
                @Override
                public void run() {
                    if (!isFinishing()) {
                        gotoUtil.replaceLogin(StartActivity.this);
                        overridePendingTransition(R.anim.base_fade_in, R.anim.base_fade_out);
                    }
                }
            }, time);
        }
    }

    private void startClean() {
        Intent intent = new Intent(StartActivity.this, CleanService.class);
        startService(intent);
    }

    private void startCleanAlias() {
        Intent intent = new Intent(StartActivity.this, CleanAliasService.class);
        startService(intent);
    }
}
